//
//  PersonalViewC.m
//  WHSport
//
//  Created by ccjoy-jimneylee on 15/4/14.
//  Copyright (c) 2015年 jimneylee. All rights reserved.
//

#import "PersonalViewC.h"
#import "UserModel.h"
#import "NewPhoneViewC.h"
#import "NickViewC.h"
#import "ModPasViewC.h"
#import "Util.h"
#import <MBProgressHUD.h>

@interface PersonalViewC (){
    NSString *sexN;
    NSString *add;
    NSString *nickOri;
    NSString *teleOri;
    NSArray *sexArray;
    NSString *pickNum;
    NSArray *provinces;
    NSArray *cities;
    NSString *newcity;
    NSString *newsex;
    NSString *newtype;
}

@end

@implementation PersonalViewC

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title =@"账户管理";
    
    _headBtn.clipsToBounds = YES;
    _headBtn.layer.cornerRadius = 30;
    
    teleOri = [NSString stringWithFormat:@"%@",
                        [UserModel sharedInstance].currentUser.userPhone];
    _teleNumLab.text = teleOri;
    nickOri = [UserModel sharedInstance].currentUser.nick;
    _nickLab.text = nickOri;
    NSString *sex = [NSString stringWithFormat:@"%@",
                     [UserModel sharedInstance].currentUser.sex];
    if ([sex isEqual:@"1"]) {
        sexN =@"男";
    }
    if ([sex isEqual:@"2"]) {
        sexN =@"女";
    }
    add = [UserModel sharedInstance].currentUser.address;
    [_sexBtn setTitle:sexN forState:UIControlStateNormal];
    [_placeBtn setTitle:add forState:UIControlStateNormal];
    
    sexArray =@[@"男",@"女"];
    //加载数据
    provinces = [[NSArray alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"ProvincesAndCities.plist" ofType:nil]];
    cities = [[provinces objectAtIndex:0] objectForKey:@"Cities"];
    
    _pickerView.hidden = YES;
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(personal:)
                                                 name:@"NOTIFICATION_PERSONAL"
                                               object:nil];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)personal:(NSNotification *)noti{
    
    if ([newtype isEqualToString:@"1"]) {
            if ([[UserModel sharedInstance].successPer isEqualToString:@"1"]) {
                MBProgressHUD *HUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
                HUD.labelText = @"性别更换成功";
                [HUD hide:YES afterDelay:1.5f];
            }
            else{
                MBProgressHUD *HUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
                HUD.labelText = @"性别更换成功失败";
                [HUD hide:YES afterDelay:1.5f];
                [_sexBtn setTitle:sexN forState:UIControlStateNormal];
            }
        }

    if ([newtype isEqualToString:@"2"]) {
        if ([[UserModel sharedInstance].successPer isEqualToString:@"1"]) {
            MBProgressHUD *HUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
            HUD.labelText = @"所在地更换成功";
            [HUD hide:YES afterDelay:1.5f];
        }
        else{
            MBProgressHUD *HUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
            HUD.labelText = @"所在地更换失败";
            [HUD hide:YES afterDelay:1.5f];
            [_placeBtn setTitle:add forState:UIControlStateNormal];
        }
    }
    
}


- (void)viewWillAppear:(BOOL)animated{
    
    [super viewWillAppear:YES];
    
   teleOri = [NSString stringWithFormat:@"%@",
               [UserModel sharedInstance].currentUser.userPhone];
    _teleNumLab.text = teleOri;
    nickOri = [UserModel sharedInstance].currentUser.nick;
    _nickLab.text = nickOri;
    NSString *sex = [NSString stringWithFormat:@"%@",
                     [UserModel sharedInstance].currentUser.sex];
    if ([sex isEqual:@"1"]) {
        sexN =@"男";
    }
    if ([sex isEqual:@"2"]) {
        sexN =@"女";
    }
    add = [UserModel sharedInstance].currentUser.address;
    [_sexBtn setTitle:sexN forState:UIControlStateNormal];
    [_placeBtn setTitle:add forState:UIControlStateNormal];
    
}

- (void)getData{
    NSString *user = [NSString stringWithFormat:@"%@",
                      [UserModel sharedInstance].currentUser.ID];
    NSString *sex = _sexBtn.titleLabel.text;
    NSString *sexNum;
    if ([sex isEqualToString:@"男"]) {
        sexNum =@"1";
    }
    if ([sex isEqualToString:@"女"]) {
        sexNum =@"2";
    }
    NSString *addrss = _placeBtn.titleLabel.text;
    NSString *nick = _nickLab.text;
    [[UserModel sharedInstance] personalModifyWithID:user sex:sexNum address:addrss nick:nick perMod:^(BOOL successed, unsigned int value) {
            if (successed) {
            }
        }];
}


- (IBAction)sexBtn:(id)sender{
    pickNum =@"1";
    _pickerView.hidden = NO;
    [_pickerView reloadAllComponents];
}
- (IBAction)placeBtn:(id)sender{
    pickNum =@"2";
    _pickerView.hidden = NO;
    [_pickerView reloadAllComponents];
}

#pragma mark - 保存图片至沙盒
- (void) saveImage:(UIImage *)currentImage withName:(NSString *)imageName
{
    
    NSData *imageData = UIImageJPEGRepresentation(currentImage, 0.5);
    // 获取沙盒目录
    
    NSString *fullPath = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:imageName];
    
    // 将图片写入文件
    
    [imageData writeToFile:fullPath atomically:NO];
}

- (IBAction)uploadBtn:(id)sender{
    UIActionSheet *sheet;
    sheet = [[UIActionSheet alloc] initWithTitle:@"选择" delegate:self
                               cancelButtonTitle:nil destructiveButtonTitle:@"取消"
                               otherButtonTitles:@"拍照",@"从相册选择",
                                nil];
    [sheet showInView:self.view];
}

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    NSUInteger sourceType = 0;
    if (buttonIndex == 0) {
        return ;
    }
    if (buttonIndex == 1) {
        sourceType = UIImagePickerControllerSourceTypeCamera;
    }
    else{
        sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
    }
    UIImagePickerController *imageController = [[UIImagePickerController alloc] init];
    imageController.delegate = self;
    imageController.allowsEditing = YES;
    imageController.sourceType = sourceType;
    [self presentViewController:imageController animated:YES completion:^{
    }];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    
    [picker dismissViewControllerAnimated:YES completion:^{
    }];
    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
    [self saveImage:image withName:@"currentImage.png"];
    
    NSString *path = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"]
                      stringByAppendingPathComponent:@"currentImage.png"];
    UIImage *save = [[UIImage alloc] initWithContentsOfFile:path];
//    NSData *imageData = UIImageJPEGRepresentation(image,0.5);
    
    [_headBtn setBackgroundImage:save forState:UIControlStateNormal];
    
    NSString *idNum =[NSString stringWithFormat:@"%@",
                      [UserModel sharedInstance].currentUser.ID];
    NSString *filename = [NSString stringWithFormat:@"%d.png",
                          arc4random()];
    NSData *imageData = UIImageJPEGRepresentation(save, 0.5);
    [[UserModel sharedInstance] personalUpImgWithID:idNum filename:filename imgdata:imageData perUp:^(BOOL successed, unsigned int value) {
        if (successed) {
            MBProgressHUD *HUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
            HUD.labelText = @"上传头像成功";
            [HUD hide:YES afterDelay:1.5f];
        }
        else{
            MBProgressHUD *HUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
            HUD.labelText = @"上传头像失败";
            [HUD hide:YES afterDelay:1.5f];
        }
    }];
    
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    
    [self dismissViewControllerAnimated:YES completion:^{
    }];
}

#pragma PickerView
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
    if ([pickNum isEqual:@"1"]) {
        return 1;
    }
    else{
        return 2;
    }
}

// returns the # of rows in each component..
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
    if ([pickNum isEqual:@"1"]) {
        return sexArray.count;
    }
    else{
        switch (component) {
            case 0:
                return [provinces count];
                break;
            case 1:
                return [cities count];
                break;
            default:
                return 0;
                break;
        }
    }
}

- (NSString *)pickerView:(UIPickerView *)pickerView
             titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    if ([pickNum isEqual:@"1"]) {
        return [sexArray objectAtIndex:row];
    }
    else{
        switch (component) {
            case 0:
                return [[provinces objectAtIndex:row] objectForKey:@"State"];
                break;
            case 1:
                return [[cities objectAtIndex:row] objectForKey:@"city"];
                break;
            default:
                return nil;
                break;
        }
    }
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{
    NSString *cityname;
    if ([pickNum isEqual:@"1"]) {
        row = [_pickerView selectedRowInComponent:0];
        NSString *type = [sexArray objectAtIndex:row];
        _pickerView.hidden = YES;
        newsex = type;
        if ([_sexBtn.titleLabel.text isEqualToString:newsex]) {
            MBProgressHUD *HUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
            NSString *message = [NSString stringWithFormat:@"已经是%@啦",_sexBtn.titleLabel.text];
            HUD.labelText = message;
            [HUD hide:YES afterDelay:1.5f];
        }
        else{
            [_sexBtn setTitle:type forState:UIControlStateNormal];
            newtype =@"1";
            [self getData];
        }
    }
    else{
        switch (component) {
            case 0:
                cities = [[provinces objectAtIndex:row] objectForKey:@"Cities"];
                [_pickerView selectRow:0 inComponent:1 animated:NO];
                [_pickerView reloadComponent:1];
                break;
            case 1:
                cityname = [[cities objectAtIndex:row] objectForKey:@"city"];
                 _pickerView.hidden = YES;
                if ([_placeBtn.titleLabel.text isEqualToString:cityname]) {
                    MBProgressHUD *HUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
                    NSString *message = [NSString stringWithFormat:@"已经在%@啦",_placeBtn.titleLabel.text];
                    HUD.labelText = message;
                    [HUD hide:YES afterDelay:1.5f];
                }
                else{
                    [_placeBtn setTitle:cityname forState:UIControlStateNormal];
                    newtype = @"2";
                    [self getData];
                    }
                break;
            default:
                break;
        }

    }
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    cell.selectionStyle =UITableViewCellSelectionStyleNone;
    if (indexPath.row == 1) {
        NewPhoneViewC *newvc = [[NewPhoneViewC alloc] initWithNibName:@"NewPhoneViewC"
                                                               bundle:nil];
        [Util presentNaviC:newvc fromController:self];
        
    }
    if (indexPath.row == 2) {
        NickViewC *nickvc = [[NickViewC alloc] initWithNibName:@"NickViewC"
                                                               bundle:nil];
        [Util presentNaviC:nickvc fromController:self];
        
    }
    if (indexPath.row == 5) {
        ModPasViewC *modvc = [[ModPasViewC alloc] initWithNibName:@"ModPasViewC"
                                                               bundle:nil];
        [Util presentNaviC:modvc fromController:self];
    }
}

@end
